package com.njit.WeStudy.control;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @author yuruiqiao
 * @date 2019-09-15
 * @description 验证码控制类
 */
@Controller
public class CaptchaController {
    @Resource
    private DefaultKaptcha kaptcha;


    /**
     * 2019-09-05
     * 设置HTTP Cache响应头信息
     * 让验证码不要有本地的cache
     * */
    @RequestMapping(path = "/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        //return a jpeg
        response.setContentType("image/png");
        //创建一个验证码
        String capText = kaptcha.createText();
        //验证码存在session中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);

        BufferedImage bi = kaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi,"png",out);
        try {
            out.flush();
        } finally {
            out.close();
        }

    }


    @Bean
    public DefaultKaptcha initCaptcha(){
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.put(Constants.KAPTCHA_BORDER,"no");
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}
